package com.ruoyi.system.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.MinUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TokenUtil;
import com.ruoyi.system.mapper.MinUserMapper;
import com.ruoyi.system.requestWarper.ParameterRequestWrapper;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author bing.li
 * @date 2021/8/22  21:16
 */
public class MyFilter implements Filter{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       HttpServletRequest req = (HttpServletRequest) request;
        String auth = req.getHeader("auth");

        if(!StringUtils.isBlank(auth)){

            final MinUserMapper minUserMapper = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(MinUserMapper.class);
            final String openid = TokenUtil.parseToken(auth);
            System.err.println("MyFilter minUser openid:"+openid);
            final MinUser minUser = minUserMapper.selectMinUserByOpenId(openid);
            System.err.println("MyFilter minUser:"+minUser);
            if(minUser != null){
                ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(req);
                ObjectMapper objectMapper = new ObjectMapper();
                final String s = objectMapper.writeValueAsString(minUser);
                requestWrapper.addParameter("minUser",s);
                chain.doFilter(requestWrapper,response);
            }
        }else{
            chain.doFilter(request,response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {

    }
}
